<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\admin\controller;
use app\common\model\CoinAddress;
use think\Db;
/**
 * wallet控制器
 */
class Wallet extends AdminBase
{
    
    /**
     * wallet列表
     */
    public function walletList()
    {
        
        $where = $this->logicwallet->getWhere($this->param);
        
        $this->assign('list', $this->logicwallet->getwalletList($where, 'a.*', 'a.create_time desc'));
        
        return $this->fetch('wallet_list');
    }
    
    /**
     * wallet添加
     */
    public function walletAdd()
    {
        
        $this->walletCommon();
        
        return $this->fetch('wallet_edit');
    }
    
    /**
     * wallet编辑
     */
    public function walletEdit()
    {
        
        $this->walletCommon();
        
        $info = $this->logicwallet->getwalletInfo(['a.id' => $this->param['id']], 'a.*');

        
        $this->assign('info', $info);
        
        return $this->fetch('wallet_edit');
    }
    
    /**
     * wallet添加与编辑通用方法
     */
    public function walletCommon()
    {
        
        IS_POST && $this->jump($this->logicwallet->walletEdit($this->param));
        

    }



    /**
     * wallet添加备用地址
     */
    public function wallet_address()
    {

        IS_POST && $this->jump($this->logicwallet->wallet_address($this->param));
        $this->assign('wallet', \app\common\model\Wallet::all(['is_virtual'=>1,'is_currency'=>1,'status'=>1]));

        return $this->fetch('wallet_address');


    }

    /**
     * wallet_address列表
     */
    public function wallet_address_list()
    {
        $where=[];
        
        !empty($this->param['wallet_id']) && $where['a.mid']=$this->param['wallet_id'];
        !empty($this->param['address']) && $where['a.address']=$this->param['address'];
        isset($this->param['type']) && $where['a.type']=$this->param['type'];
        $this->assign('list', $this->logicwallet->getwalletAddressList($where, 'a.*', 'a.create_time desc'));
        $this->assign('wallet',\app\common\model\Wallet::all(['status'=>1,'is_virtual'=>1,'is_currency'=>1]));
        $this->assign('param',$this->param);
        return $this->fetch('wallet_address_list');
    }
    

    /**
     * 数据状态设置
     */
    public function setStatus()
    {
        
        $this->jump($this->logicAdminBase->setStatus('wallet', $this->param));
    }
    
    
    //用户充值地址列表
    public function user_recharge_list(){

        $where['wallet_id'] = ["in",[6,7,8]];

        !empty($this->param['search_data']) && $uid=\app\common\model\Member::where(['username|mobile'=>$this->param['search_data']])->value('id');

        !empty($uid) && $where['user_id']=$uid;
        !empty($this->param['is_money']) && $where['number']=['gt',0];
        
    	$users  = Db::name("user_account")
            ->field("user_id")
            ->where($where)
            ->group("user_id")
            ->paginate(10,false,['query'=>$this->param]);

        $items = $users->items();

        foreach ($items as $k=>$v){
            $items[$k]['id'] = $k;
            
            $items[$k]['userinfo'] = Db::name("member")->field('id,username,mobile,is_company,is_king,is_shop,cover_id')->where(["id"=>$v['user_id']])->find();

            $items[$k]['userinfo']['head_pic'] = get_picture_url($items[$k]['userinfo']['cover_id'],false);

            $items[$k]['address'] = array();
            $items[$k]['address']['eth'] = Db::name("user_account")->field('blockchain_address2,number')->where(["user_id"=>$v['user_id'],"wallet_id"=>6])->find();
            $items[$k]['address']['btc'] = Db::name("user_account")->field('blockchain_address2,number')->where(["user_id"=>$v['user_id'],"wallet_id"=>7])->find();
            $items[$k]['address']['usdt'] = Db::name("user_account")->field('blockchain_address2,number')->where(["user_id"=>$v['user_id'],"wallet_id"=>8])->find();
            $items[$k]['address']['ccie'] = Db::name("user_account")->field('blockchain_address2,number')->where(["user_id"=>$v['user_id'],"wallet_id"=>18])->find();
        }
        
        $total=array();
        $total['eth']=Db::name("user_account")->where(["wallet_id"=>6])->sum("number");
        $total['btc']=Db::name("user_account")->where(["wallet_id"=>7])->sum("number");
        $total['usdt']=Db::name("user_account")->where(["wallet_id"=>8])->sum("number");
        $total['ccie']=Db::name("user_account")->where(["wallet_id"=>18])->sum("number");
        
        $total['summary']=Db::name("transfer")->where(["type"=>25,"status"=>1])->sum("number")??0;

//数量统计

        $this->assign('users',$users);
        $this->assign("list",$items);
        $this->assign("total",$total);
    	
    	return $this->fetch('user_recharge_list');
    }
    
    //更新余额
    public function update_number(){
        $user_id = input("user_id");
        $user_accounts = Db::name("user_account")->where(["user_id"=>$user_id,"wallet_id"=>["in",[6,7,8,18]]])->select();
        if(empty($user_accounts)){
            $this->error("参数错误");
        }
        $url = COIN_URL."/api/v1/address/balance";
        $is_pi=input("is_pi");
        foreach ($user_accounts as $k=>$v){
            $wallet = Db::name("wallet")->where(["id"=>$v["wallet_id"]])->find();
            $symbol = strtolower($wallet['symbol']);
            $address = $v['blockchain_address2'];

            if($symbol == "eth"){
                //ETH
                $post_data = array(
                    "code" => "ETH",
                    "address" => $address,
                    "nonce_str" => rand(1000,9000)
                );

            }elseif($symbol == "usdt"){
                //ETH 代币
                $post_data = array(
                    "code" => "USDT",
                    "address" => $address,
                    "nonce_str" => rand(1000,9000)
                );
            }elseif($symbol == "btc"){
                //BTC
                $post_data = array(
                    "code" => "BTC",
                    "address" => $address,
                    "nonce_str" => rand(1000,9000)
                );
            }elseif($symbol == "ccie"){
                //CCIE
                $post_data = array(
                    "code" => "ETH/CCIE",
                    "address" => $address,
                    "nonce_str" => rand(1000,9000)
                );
            }
            $post_data['contract_address'] =$wallet['contractaddress'];
            $post_data['filter'] ='geth';
            $sign = md5(asc_sort($post_data).'&key='."79ba9e912e708a0a3177df0641be1e5a");

            $post_data['sign'] = $sign;
            
            $result=json_decode(mycurl($url,$post_data,1),true);

            if(!empty($result['status']) && $result['status'] == 1){
                $number = empty($result['data'])?0:(float)$result['data'];
                Db::name("user_account")->where(["id"=>$v["id"]])->update(["number"=>$number]);
                if(!empty($is_pi)){
                    return ['code'=>1,'msg'=>'查询成功','data'=>$number];
                }else{
                    $this->success("查询成功，当前数量：".$number);
                }


            }else{
                $this->error(empty($result['msg'])?"查询失败":$result['msg']);
            }
        }
    }

    //转入汇总地址
    public function transfer_to_summary(){
        $user_id = input("user_id");
        $user_accounts = Db::name("user_account")->where(["user_id"=>$user_id,"wallet_id"=>["in",[6,8]]])->select();

        if(empty($user_accounts)){
            $this->error("参数错误");
        }

        // $url = COIN_URL."/api/v1/transfer/add";

        foreach ($user_accounts as $k=>$v){
            
                $wallet = Db::name("wallet")->where(["id"=>$v["wallet_id"]])->find();
                if(empty($wallet)){
                    continue;
                }

                $from = $v["blockchain_address2"];

                $to = $wallet["wallet_address2"];
                $number = $v["number"];
                $symbol = strtolower($wallet['symbol']);
                if(empty($wallet)){
                    continue;
                }
                
                if(empty($from)){
                    continue;
                }
               
                $is_from = Db::name("user_account")->where(["blockchain_address2"=>$from])->count();
                if(empty($is_from)){
                    continue;
                }
               
                if(empty($to)){
                    continue;
                }
            
                if(empty($number) || $number <= 0){
                    continue;
                }
                
                // $password = CoinAddress::where(['address'=>$from])->value('label');

                // $contractaddress = $wallet['contractaddress'];
            //     $post_data = array(
            //        "code" => "ETH",
            //        "from_address" => $from,
            //        "to_address" => $to,
            //        "number" => $number,
            //        "password" => $password,
            //        "nonce_str" => rand(1000,9999)
            //   );
            //     $post_data['contract_address'] = $contractaddress;
            //     $post_data['private_key'] = '';
            //     $post_data['gas_limit'] = '';
            //     $post_data['gas_price'] = '';
            //   $sign = md5(asc_sort($post_data).'&key='."79ba9e912e708a0a3177df0641be1e5a");
            //     $post_data['sign'] = $sign;


            //     $dat=json_decode(mycurl($url,$post_data,1),true);
                
            //     if($dat['status']==1){
                    // $request_arr=$dat['data'];
                    //成功
                    $data['wallet_id'] = $v['wallet_id'];
                    $data['user_id'] =$user_id;
                    $data['type'] = 1;
                    $data['from_address'] = $from;
                    $data['to_address'] = $to;
                    $data['number'] = $number;
                    $data['create_time'] = time();
                    $data['update_time'] = time();
                    $data['status'] = 0;
                    $res = Db::name("user_address_transfer")->insert($data);     
                    if(!$res){
                        $this->error('提交失败');
                    }
                // }else{
                //     $this->error('汇总失败');
                // }            
        }
        $this->success('汇总成功');
    }


    //批量转入汇总地址
    public function transferall(){
        $ids  = $_POST['ids'];
        if (empty($ids)){
            $this->error("用户不能为空");
        }
        // $url = COIN_URL."/api/v1/transfer/add";
        $walletid_arr = [6,18];
        foreach($ids as $id){
            $user_accounts = Db::name("user_account")->where(["user_id"=>$id,"wallet_id"=>['in',$walletid_arr]])->select();
            if(empty($user_accounts)){
                $this->error("用户地址不存在");
            }
            foreach($user_accounts as $user_account){

                $wallet = Db::name("wallet")->where(["id"=>$user_account["wallet_id"]])->find();
                if(empty($wallet)){
                    continue;
                }

                $from = $user_account["blockchain_address2"];

                $to = $wallet["wallet_address2"];
                $number = $user_account["balance"];
                $symbol = strtolower($wallet['symbol']);
                if(empty($wallet)){
                    continue;
                }
                if(empty($from)){
                    continue;
                }
                $is_from = Db::name("user_account")->where(["blockchain_address2"=>$from])->count();
                if(empty($is_from)){
                    continue;
                }
                if(empty($to)){
                    continue;
                }

                if(empty($number) || $number <= 0){
                    continue;
                }

            //     $password = CoinAddress::where(['address'=>$from])->value('label');

            //     $contractaddress = $wallet['contractaddress'];
            //     $post_data = array(
            //         "code" => "ETH",
            //        "from_address" => $from,
            //        "to_address" => $to,
            //        "number" => $number,
            //        "password" => $password,
            //        "nonce_str" => rand(1000,9999)
            //   );
            //     $post_data['contract_address'] = $contractaddress;
            //     $post_data['private_key'] = '';
            //     $post_data['gas_limit'] = '';
            //     $post_data['gas_price'] = '';
            //     $sign = md5(asc_sort($post_data).'&key='."79ba9e912e708a0a3177df0641be1e5a");
            //     $post_data['sign'] = $sign;


            //     $dat=json_decode(mycurl($url,$post_data,1),true);
           
                // if($dat['status']==1){
                    // $request_arr=$dat['data'];
                    //成功
                    $data['wallet_id'] = $wallet['id'];
                    $data['user_id'] =$id;
                    $data['type'] = 2;
                    $data['from_address'] = $from;
                    $data['to_address'] = $to;
                    $data['number'] = $number;
                    $data['create_time'] = time();
                    $data['update_time'] = time();
                    $data['status'] = 0;
                    $res = Db::name("user_address_transfer")->insert($data);     
                    if(!$res){
                        $this->error('提交失败');
                    }else{
                        $this->success("提交成功");
                    }
                //    }else{
                //     return ['code'=>1,'msg'=>$dat['msg']];
                //    }

            }
        }
    }



    //矿工费转帐
    public function mine_transfer(){
        if(empty($_POST)){
            $user_id = $_GET['user_id'];
            $this->assign('user_id',$user_id);
            return $this->fetch();
        }else{
            $symbol = input('symbol','eth');
            $user_id = input("user_id");
            $number = input("number",getConfig('transfer_miner_fee'));

            $wallet = Db::name("wallet")->where(["symbol"=>$symbol])->find();

            // $url = COIN_URL."/api/v1/transfer/add";
            $from = $wallet["wallet_address"];
            $to = Db::name("user_account")->where(["user_id"=>$user_id,"wallet_id"=>$wallet["id"]])->find()["blockchain_address2"];
            if(empty($wallet)){
                $this->error("货币不存在");
            }
            if(empty($from)){
                $this->error("转出地址错误");
            }
            if(empty($to)){
                $this->error("转入地址错误");
            }
            if(empty($number)){
                $this->error("数量不得为空");
            }
        //     $password = CoinAddress::where(['address'=>$from])->value('label');
        //     $contractaddress = $wallet['contractaddress'];
        //     $host = $wallet['rpc_host'];
        //     $post_data = array(
        //         "filter"=>"geth",
        //         "code" => "ETH",
        //        "from_address" => $from,
        //        "to_address" => $to,
        //        "number" => $number,
        //        "password" => $password,
        //        "nonce_str" => rand(1000,9999)
        //   );
        //     $post_data['contractaddress'] = $contractaddress;
        //     $post_data['private_key'] = '';
        //     $post_data['gas_limit'] = '';
        //     $post_data['gas_price'] = '';

        //     $sign = md5(asc_sort($post_data).'&key='."79ba9e912e708a0a3177df0641be1e5a");
        //     $post_data['sign'] = $sign; 
        //     //  dump(json_encode($post_data));
        //     $dat=json_decode(mycurl($url,$post_data,1),true);
            // dump($dat);exit;
            // if($dat['msg']=="转账失败：insufficient funds for gas * price + value"){
            //     return ['code'=>0,'msg'=>'余额不足'];
            // }
            // if($dat['status']==1){
                //成功
                // $request_arr=$dat['data'];
                $data['wallet_id'] = $wallet['id'];
                    $data['user_id'] =$user_id;
                    $data['type'] = 1;
                    $data['from_address'] = $from;
                    $data['to_address'] = $to;
                    $data['number'] = $number;
                    $data['create_time'] = time();
                    $data['update_time'] = time();
                    $data['status'] = 0;
                    $res = Db::name("user_address_transfer")->insert($data);     
                    if(!$res){
                        $this->error('提交失败');
                    }
                

            //    }else{
            //     return ['code'=>0,'msg'=>'转帐失败'];
            //    }      
        }
        $this->success('提交成功');
    }
    //转账
    public function transfer(){
    	$from = input("from");
		$to = input("to");
		$number = input("number");
		$symbol = strtolower(input("symbol"));
		
		$wallet = Db::name("wallet")->where(["symbol"=>$symbol])->find();
		if(empty($wallet)){
			$this->error("货币不存在");
		}
		if(empty($from)){
			$this->error("转出地址错误");
		}
		$is_from = Db::name("user_account")->where(["blockchain_address2"=>$from])->count();
		if(empty($is_from)){
			$this->error("转出地址不在用户地址库");
		}
		if(empty($to)){
			$this->error("请输入收款地址");
		}
		if($wallet['wallet_address'] != $to){
			$this->error("收款地址不是汇总地址");
		}
		if(empty($number) || $number <= 0){
			$this->error("请输入数量");
		}

        $url = COIN_URL."/api/v1/coin/transfer/add";
		$password = $wallet['wallet_password'];
		$contractaddress = $wallet['contractaddress'];
    	$host = $wallet['rpc_host'];

    	if($symbol == "eth"){

    		//eth转账

	  	    $post_data = array(
	  	        "code" => "ETH",
	     		"from_address" => $from,
	     		"to_address" => $to,
	     		"number" => $number,
	     		"password" => $password,
	     		"nonce_str" => rand(1000,9999)
		    );

    	}elseif($symbol == "usdt" ){
    		//eth 代币转账
            $post_data = array(
                "code" => "USDT",
                "from_address" => $from,
                "to_address" => $to,
                "number" => $number,
                "password" => $password,
                "nonce_str" => rand(1000,9999)
            );
    	}elseif($symbol == "btc"){
    		//btc转账
            $post_data = array(
                "code" => "BTC",
                "from_address" => $from,
                "to_address" => $to,
                "number" => $number,
                "password" => $password,
                "nonce_str" => rand(1000,9999)
            );
    	}
        $sign = md5(asc_sort($post_data).'&key='."79ba9e912e708a0a3177df0641be1e5a");

        $post_data['sign'] = $sign;

        $result=json_decode(mycurl($url,$post_data,1),true);

        if(!empty($result['status']) && $result['status'] == 1){
            $this->success($result['data']);
        }else{
            if($result['msg'] == 'insufficient funds for gas * price + value'){
                $msg = lang("钱包余额不足");
            }else{
                $msg = $result['msg'];
            }
            $this->error($result['msg']);
        }
    }
    

    //批量转入矿工费
    public function mine_all(){
        if(empty($_POST)){
            $ids = $_GET['ids'];
            $this->assign('ids',$ids);
            return $this->fetch();
        }else{
            $symbol = input('symbol','eth');
            $ids = input("ids");
            
            $number = input("number",getConfig('transfer_miner_fee'));

            $wallet = Db::name("wallet")->where(["symbol"=>$symbol])->find();

            $url = COIN_URL."/api/v1/transfer/add";
            $from = $wallet["wallet_address"];
            $ids = explode(',',$ids);
            
            foreach($ids as $id){
                $to = Db::name("user_account")->where(["user_id"=>$id,"wallet_id"=>$wallet["id"]])->find()["blockchain_address2"];
                if(empty($wallet)){
                    $this->error("货币不存在");
                }
                if(empty($from)){
                    $this->error("转出地址错误");
                }
                if(empty($to)){
                    $this->error("转入地址错误");
                }
                if(empty($number)){
                    $this->error("数量不得为空");
                }
            //     $password = CoinAddress::where(['address'=>$from])->value('label');
            //     $contractaddress = $wallet['contractaddress'];
            //     $host = $wallet['rpc_host'];
            //     $post_data = array(
            //         "filter"=>"geth",
            //         "code" => "ETH",
            //        "from_address" => $from,
            //        "to_address" => $to,
            //        "number" => $number,
            //        "password" => $password,
            //        "nonce_str" => rand(1000,9999)
            //   );
            //     $post_data['contractaddress'] = $contractaddress;
            //     $sign = md5(asc_sort($post_data).'&key='."79ba9e912e708a0a3177df0641be1e5a");
            //     $post_data['sign'] = $sign; 
            //     $dat=json_decode(mycurl($url,$post_data,1),true);
            //     if($dat['msg']=="转账失败：insufficient funds for gas * price + value"){
            //         return ['code'=>0,'msg'=>'余额不足'];
            //     }
            //     if($dat['status']==1){
                    //成功
                    // $request_arr=$dat['data'];
                    $data['wallet_id'] = $wallet['id'];
                    $data['user_id'] =$id;
                    $data['type'] = 1;
                    $data['from_address'] = $from;
                    $data['to_address'] = $to;
                    $data['number'] = $number;
                    $data['create_time'] = time();
                    $data['update_time'] = time();
                    $data['status'] = 0;
                    $res = Db::name("user_address_transfer")->insert($data);     
                    if(!$res){
                        $this->error('提交失败');
                    }
                
                //     return ['code'=>1,'msg'=>'转帐成功'];
                //    }else{
                //     return ['code'=>0,'msg'=>'转帐失败'];
                //    }
            }
            $this->error('提交成功');
            
               
        }
    }

    /**
     * 钱包转帐记录
     */
    public function user_transfer_list(){
        $list = Db::name("user_address_transfer")->where("1=1")->select();
        foreach($list as $k=>$v){
            $list[$k]["user_name"] = Db::name("member")->where(["id"=>$v["user_id"]])->find()["username"];
            $list[$k]["wallet_name"] = Db::name("wallet")->where(["id"=>$v["wallet_id"]])->find()["name"];
        }
        $total = Db::name("user_address_transfer")->where("1=1")->count();
        $this->assign("list",$list);
        $this->assign("total",$total);
    
    	
    	return $this->fetch('user_transfer_list');
    }

    /**
     * 转账重新发起
     */
    public function re_transfer(){
        $id = $_GET['id'];
        $transfer = Db::name("user_address_transfer")->where(["id"=>$id])->find();
        if(empty($transfer)){
            $this->error('数据为空');
        }else{
            try{
                Db::name("user_address_transfer")->where(["id"=>$id])->update(["status"=>0]);
            }catch(\Exception $e){
                $this->error("发起失败".$e->getMessage());
            }
            $this->success("重新发起成功");
        }
    }


}
